//
//  SWAlbumCollectionCell.swift
//  ChildStory
//
//  Created by linhan on 2016/11/24.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWAlbumCollectionCell: UICollectionViewCell,SWALPhotoDelegate
{
    weak var photo:SWALPhoto? {
        didSet {
            photo?.delegate = self
            if _inited && _change
            {
                layoutSubviews()
            }
        }
    }
    
    weak var delegate:CollectionViewCellDelegate?
    
    private var _change:Bool = true
    
    private var _inited:Bool = false
    
    private var _label:UILabel = UILabel()
    private var _thumbImageView:UIImageView = UIImageView()
    private var _addBtn:UIButton = UIButton(type: .custom)
    
    override init(frame: CGRect)
    {
        super.init(frame: frame)
        setup()
    }
    
    deinit
    {
        //trace("DEINIT SWAssetCollectionCell")
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        contentView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        _thumbImageView.frame = bounds
        _thumbImageView.contentMode = .scaleAspectFill
        _thumbImageView.clipsToBounds = true
        contentView.addSubview(_thumbImageView)
        
        _addBtn.setImage(UIImage(named:"album_btn_add"), for: .normal)
        _addBtn.sizeToTouchEasy()
        _addBtn.center = CGPointMake(width - 12, 12)
        _addBtn.addTarget(self, action: #selector(addBtnTapped), for: .touchUpInside)
        contentView.addSubview(_addBtn)
        
        _inited = true
    }
    
    override func prepareForReuse()
    {
        super.prepareForReuse()
        _change = true
    }
    
    func photoThumbChanged(_ photo:SWALPhoto, thumb:UIImage)
    {
        _thumbImageView.image = thumb
    }
    
    override func layoutSubviews()
    {
        super.layoutSubviews()
        
        if let photo = photo , _change
        {
            _change = false
            _thumbImageView.image = nil
            if let thumb = photo.thumbnail
            {
                _thumbImageView.image = thumb
            }
        }
    }
    
    @objc private func addBtnTapped()
    {
        delegate?.collectionViewCell(self, click: CallbackAction.Add, argument: nil)
    }
    
}
